import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

/***********************************************************************
 * Base class
 * 
 * Implements the base artifact
 * 
 * Signature: public static Base create (String name, Coord position, int
 * energy); public void install (); public void destroy (); public Coord
 * position (); public String name (); public void report (String message);
 * public void changePosition (Coord target); public boolean isOrbitable ();
 * public void takeDamage (int damage); public abstract char display (); public
 * abstract String toString (); public int energy ();
 ***********************************************************************/

class Base extends Artifact {
  
  private int energy;
  
  protected Base(String n, Coord p, int e) {
    super(n, p);
    this.energy = e;
  }
  
  public static Base create(String n, Coord p, int e) {
    Base b = new Base(n, p, e);
    b.install();
    return b;
  }
  
  public char display() {
    return '@';
  }
  
  public int energy() {
    return this.energy;
  }
  
  public void takeDamage(int d) {
    if (d < 0)
      throw new IllegalArgumentException("Ship.takeDamage()");
    energy = energy - d;
    if (energy < 0)
      energy = 0;
    report("taking damage " + d);
    report("energy down to " + energy);
    if (energy == 0) {
      report("AAAAARRRGHHHH! *BOOM*");
      destroy();
    }
  }
  
  public String toString() {
    return "Base " + this.name() + " " + this.position().toString();
  }
  
  public boolean isOrbitable() {
    return true;
  }
  
  public static Base fromJSON(JSONObject json) {
    try {
      if(json.getString("className").equals("Base")) {
        return new Base(json.getString("name"),
                        new Coord().fromJSON(json.getJSONObject("position")),
                        json.getInt("energy"));
      } else {
        System.err.println("\"" + json.toString() + "\" does not represent a Base.");
        throw new RuntimeException("Cannot parse JSON, it is not a Base!");
      }
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace");
    }
    
  }

  @Override
  public String toJSONString() {
    try {
      return new JSONStringer()
                        .object() 
                          .key("className")
                          .value("Base")
                          .key("name")
                          .value(this.name())
                          .key("position")
                          .value(this.position())
                          .key("energy")
                          .value(this.energy())
                        .endObject().toString();
    } catch (JSONException e) {
      e.printStackTrace();
      throw new RuntimeException("Unrecoverable JSON error, see above stack trace.");
    }
  }
}
